package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {


    @Autowired
    private RestHighLevelClient client;


    @Override
    public PageResult search(RequestParams params) {
        try {
            //创建request对象
            SearchRequest request = new SearchRequest("hotel");
            //将判断条件抽取
            buildBasicQuery(params, request);

            Integer page = params.getPage(); //当前页
            Integer size = params.getSize(); //分页参数
            //设置分页
            request.source().from((page - 1) * size);
            request.source().size(size);

            request.source().highlighter(new HighlightBuilder()
                    .field("name")
                    .preTags("<em>")
                    .postTags("</em>")
                    .requireFieldMatch(false));
            //用户评价降序
            String sortBy = params.getSortBy();
            if (StringUtils.isNotBlank(sortBy)) {
                String score = "score";
                String price = "price";

                //判断是根据价格还是评价排序
                if (sortBy.equals(score)) {
                    request.source().sort("score", SortOrder.DESC);
                }
                if (sortBy.equals(price)) {
                    request.source().sort("price", SortOrder.ASC);
                }
            }
            //距离排序
            String location = params.getLocation();
            if (StringUtils.isNotBlank(location)) {
                request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS));
            }

            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //直接调用抽取的解析代码
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 限定聚合范围
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        //创建搜索请求
        try {
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();
            //构建query条件 锁定聚合文档的范围
            buildBasicQuery(params, request);
            source.aggregation(AggregationBuilders.terms("cityAgg")
                    .field("city").size(20));
            source.aggregation(
                    AggregationBuilders.terms("starNameAgg")
                            .field("starName").size(20)
            );
            source.aggregation(
                    AggregationBuilders.terms("brandAgg")
                            .field("brand").size(20)
            );

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> map = new HashMap<>();
            //获取聚合结果
            Aggregations aggregations = response.getAggregations();
            List<String> cityAgg = getAggResoult(aggregations, "cityAgg");
            map.put("city", cityAgg);
            List<String> starNameAgg = getAggResoult(aggregations, "starNameAgg");
            map.put("starName", starNameAgg);
            List<String> brandAgg = getAggResoult(aggregations, "brandAgg");
            map.put("brand", brandAgg);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 自动补全
     *
     * @param key
     * @return
     */
    @Override
    public List<String> getSuggestions(String key) {
        //创建请求
        SearchRequest request = new SearchRequest("hotel");
        //获取source
        SearchSourceBuilder source = request.source();
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        source.suggest(suggestBuilder.addSuggestion("suggestions",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(key).skipDuplicates(true).size(10))
        );
        try {
            //发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            List<String> lists = new ArrayList<>();

            Suggest suggest = response.getSuggest();
            //根据查询补全名称
            CompletionSuggestion suggestion = suggest.getSuggestion("suggestions");
            //获取options
            List<CompletionSuggestion.Entry.Option> list = suggestion.getOptions();
            for (CompletionSuggestion.Entry.Option option : list) {
                String text = option.getText().toString();
                lists.add(text);
            }
            return lists;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    //监听添加或修改的消息
    @Override
    public void insertAndUpdateById(Long id) {
        Hotel hotel = getById(id);
        //转换为文档类型
        HotelDoc hotelDoc = new HotelDoc(hotel);
        //准备request文档
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //转换为json文档
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
        //发送请求
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }

    }

    //监听删除消息
    @Override
    public void deleteById(Long id) {
        DeleteRequest request = new DeleteRequest("hotel", String.valueOf(id));
        //发送请求
        try {
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

    }


    private List<String> getAggResoult(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> list = terms.getBuckets();
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : list) {
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }


    //抽取的条件过滤方法
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //获取前端传入params中的key
        String key = params.getKey();
        //判断key是否为空
        if (StringUtils.isNotBlank(key)) {
            //不为空根据key查询数据
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            //为空则查询全部
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        //品牌
        String brand = params.getBrand();
        //判断前端是否传入品牌数据
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        //城市
        String city = params.getCity();
        //判断前端是否传入城市数据
        if (StringUtils.isNotBlank(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city", city));
        }
        //星级
        String starName = params.getStarName();
        //判断前端是否传入星级数据
        if (StringUtils.isNotBlank(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));
        }
        //价格范围
        Integer maxPrice = params.getMaxPrice();
        Integer minPrice = params.getMinPrice();
        //判断前端是否传入城市数据
        if (maxPrice != null && minPrice != null) {
            maxPrice = maxPrice == 0 ? Integer.MAX_VALUE : maxPrice;
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice)
            );
        }

        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
        request.source().query(functionScoreQueryBuilder);
    }

    //解析
    private PageResult handleResponse(SearchResponse response) {

        //获取响应对象
        SearchHits hits = response.getHits();
        //获取响应数据总条数
        long totalHits = hits.getTotalHits().value;
        System.out.println("共查询到" + totalHits + "条数据");
        //获取文档数据
        SearchHit[] hitsHits = hits.getHits();
        //创建数组
        List<HotelDoc> list = new ArrayList<>();
        //遍历文档数据
        for (SearchHit hit : hitsHits) {
            //获取文档数据json格式字符串
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //高亮结果处理
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            //判断高亮是否为空
            if (!CollectionUtils.isEmpty(highlightFields)) {
                //获取高亮字段
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    //取出高亮结果数组中的第一个即为高亮字段
                    String name = highlightField.getFragments()[0].string();
                    hotelDoc.setName(name);
                }
            }
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                Object values = sortValues[0];
                hotelDoc.setDistance(values);
            }
            //存入数组
            list.add(hotelDoc);
        }
        return new PageResult(totalHits, list);
    }
}
